<template>
  <el-card style="height: 500px">
    <div slot="header" style="text-align: center;font-weight: bold;">{{title}}</div>
    <el-form>
     <el-form-item lable="文档上传">
      <el-upload
    class="custom-upload"
    action="http://localhost:9999/upload1"
    :on-preview="handlePreview"
    :on-remove="handleRemove"
    :before-remove="beforeRemove"
    :limit="5"
    :auto-upload="false"
    :on-change="handleChange"
    :file-list="fileList"
    :multiple="true"
    :style="{width: '473px', borderRadius: '4px'}"
  >
  <el-button
      slot="trigger"
      type="primary"
      :loading="uploading"
      style="width: 100%; height: 48px; font-size: 18px; border-radius: 4px;"
    >
      {{ uploading ? '上传中...' : '点击上传' }}
    </el-button>
    <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
  </el-upload>
    </el-form-item> 

    <el-select v-model="value" placeholder="请选择文件类型">
     
     <el-option
       v-for="item in options"
       :key="item.value"
       :label="item.label"
       :value="item.value">
     </el-option>
   </el-select>
    <br>
    <p v-if="message">{{ message }}</p>
    <p> 
      <el-link v-if="successLink" :type="successLinkType" :disabled="successLinkDisabled" :href="successLink">{{ successLinkText }}</el-link>
    </p>
    </el-form>
</el-card>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      uploadedFiles: [], // 保存上传的文件
      fileList: [], 
      uploading: false, // 控制上传按钮加载状态
      title:"扫描件导入",
      message: '',
      successLink: null, // 保存成功链接
      successLinkType: 'success', // 链接类型
      successLinkDisabled: false, // 是否禁用链接
      successLinkText: '下载图片', // 链接显示的文本
      ocrResult: null, // 保存OCR识别结果
      selectedFileName: '', // 新增这一行来存储文件名
      options: [{
          value: '0',
          label: '重要文件'
        }, {
          value: '1',
          label: '图像文件'
        }, {
          value: '2',
          label: '文本文件'
        }, {
          value: '3',
          label: '视频文件'
        }],
        value:'',
      };
  },
  methods: {
    handlePreview(file) {
      console.log(file);
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${ file.name }？`);
    },

    handleChange(file, fileList) {
  this.fileList = fileList;
  if (file.status === 'ready') {
    this.uploadFile(file, fileList);
  }
},
    
      async uploadFile(file) {
      this.uploading = true;
      const formData = new FormData();
      formData.append('file', file.raw);

      try {
        const response = await axios.post('http://localhost:9999/upload1', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });

        console.log(response.data);
        this.$message({
          type: 'success',
          message: '文件导入成功!'
        });

        const url = response.data;
        let successLink;

        const pngEndIndex = url.indexOf('.png');
        const jpgEndIndex = url.indexOf('.jpg');
        const jpegEndIndex = url.indexOf('.jpeg');
        const pdfEndIndex = url.indexOf('.pdf');


if (pngEndIndex !== -1) {
  successLink = url.substring(0, pngEndIndex + 4); 
  console.log("已找到png文件")
} else if (jpgEndIndex !== -1) {
  successLink = url.substring(0, jpgEndIndex + 4); 
  console.log("已找到jpg文件")
} else if (jpegEndIndex !== -1) {
  successLink = url.substring(0, jpegEndIndex + 5); 
}  else if (pdfEndIndex !== -1) {
  successLink = url.substring(0, pdfEndIndex + 4); 
} else {
   console.error('Unsupported image format in the URL.');
}

        // 将文件信息添加到 uploadedFiles 数组中
        this.uploadedFiles.push({
          name: file.name,
          link: successLink,
          type: this.value,
          ocrResult: null // 默认值，稍后更新
        });

        // 发送文件路径到服务器获取 OCR 结果
        await this.sendFilePathToServer(file.name);

        // 确保所有前置操作成功后，最后调用 addFile 方法
        if (!this.value) {
          alert('请先选择文件类型!');
        } else {
          await this.addFile(file.name);
        }

        this.uploading = false;
      } catch (error) {
        this.uploading = false;
        this.$message.error('文件上传失败！');
        console.error(error);
      }
    },
    async sendFilePathToServer(fileName) {
      const file = this.uploadedFiles.find(f => f.name === fileName);
      if (!file) {
        console.error('找不到文件:', fileName);
        return;
      }

      try {
        const response = await axios.get('http://localhost:9999/getOCRResult', {
          params: { file: fileName }
        });

        console.log('后端响应：', response.data);
        file.ocrResult = response.data;
      } catch (error) {
        console.error('请求失败：', error);
        file.ocrResult = null;
      }
    },
    async addFile(fileName) {
      const file = this.uploadedFiles.find(f => f.name === fileName);
      if (!file) {
        console.error('找不到文件:', fileName);
        return;
      }

      try {
        const response = await axios.post('http://localhost:9999/addFile', {
          fileName: file.name,
          filePath: file.link,
          text: file.ocrResult,
          type: this.value
        }, {
          headers: {
            'Content-Type': 'application/json'
          }
        });
          console.log('文本信息发送成功', response.data);
      } catch (error) {
        console.error('请求失败：', error);
        file.ocrResult = null;
      }
    },

   
    },
  mounted() {
    window.addEventListener('beforeunload', this.handleBeforeUnload);
  }
};
</script>
<style scoped>
.custom-upload {
  display: inline-block;
}
</style>